package com.bizdk.generator.controller.gen;

import cn.hutool.core.io.IoUtil;
import com.bizdk.generator.common.utils.DateUtils;
import com.bizdk.generator.common.utils.R;
import com.bizdk.generator.dto.gen.GeneratorInfo;
import com.bizdk.generator.validate.group.GeneratorInfoGroup;
import com.bizdk.generator.service.GeneratorService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成
 */
@AllArgsConstructor
@Controller
@RequestMapping("/gen/generator")
public class GeneratorController {
    
    private GeneratorService service;
    
    
    /**
     * 生成代码 下载文件
     */
    @PostMapping("/download")
    public void download(@RequestBody GeneratorInfo generatorInfo, HttpServletResponse response) throws Exception {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ZipOutputStream zip = new ZipOutputStream(outputStream);) {
            
            service.downloadCode(generatorInfo, zip);
            // zip压缩包数据
            byte[] data = outputStream.toByteArray();
            
            response.reset();
            response.setHeader("Content-Disposition",
                    "attachment; filename=code" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".zip");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IoUtil.write(response.getOutputStream(), false, data);
        } catch (Exception ex) {
        }
    }
    
    /**
     * 生成代码（自定义目录）
     */
    @ResponseBody
    @PostMapping("/code")
    public R<String> code(@Validated(value = {GeneratorInfoGroup.Code.class}) @RequestBody GeneratorInfo generatorInfo,
            HttpServletResponse response) throws Exception {
        // 生成代码
        service.generatorCode(generatorInfo);
        return R.ok();
    }
    
    /**
     * 预览代码
     */
    @ResponseBody
    @GetMapping("/preview")
    public R<Map<String, String>> preview(GeneratorInfo generatorInfo) throws IOException {
        Map<String, String> dataMap = service.previewCode(generatorInfo);
        return R.ok(dataMap);
    }
    
}